﻿<%@ WebHandler Language="C#" Class="RTGS.Web.ajaxhandler.rtgs.stp_record_detail_o_clearing" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RTGS.Library.Enum;
using RTGS.Library.DataAccess.Rtgs;
using RTGS.Library.Entities.Rtgs;
using RTGS.Web.support;
using System.Configuration;
using RTGS.Library.DataAccess.UserManagement;
using RTGS.Library.Entities.UserManagement;

namespace RTGS.Web.ajaxhandler.rtgs
{

 public class stp_record_detail_o_clearing : BaseHandler
    {

        private stpRecordDetailORepo strRecordDal = new stpRecordDetailORepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
    
        private string MethodName = string.Empty;
        private string typeOutgoing = string.Empty;

        private sysTLogRepo logDal = new sysTLogRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
        private sysTLog log = new sysTLog();

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];
            if (context.Request.Params["typeOutgoing"] != null)
                typeOutgoing = context.Request.Params["typeOutgoing"];

            context.Response.Clear();
            context.Response.Buffer = true;

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context));
                    break;
                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();

        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region CRUD Handler

        private string Insert(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            stpRecordDetailO obj = new stpRecordDetailO();
            obj.recordDetailOrecordStatus = "WA";
            obj.recordDetailOrecordRsncde = "000";
            obj.recordDetailOtrRecordtype = "1";
            obj.recordDetailOstMemberinfo = "/FEAB/R/PTR/LOCAL-LOCAL";
            obj.recordDetailOrecordMt = "202";
           
            
            if (context.Request.Params["isclearing"] != null)
            {
                if(context.Request.Params["isclearing"]=="prefundkredit")
                    obj.recordDetailOtrTransactioncode = "300";

                if (context.Request.Params["isclearing"] == "prefunddebit")
                    obj.recordDetailOtrTransactioncode = "310";

                if (context.Request.Params["isclearing"] == "topprefundkredit1")
                    obj.recordDetailOtrTransactioncode = "301";
                
                if (context.Request.Params["isclearing"] == "topprefundkredit2")
                    obj.recordDetailOtrTransactioncode = "302";

                if (context.Request.Params["isclearing"] == "topprefunddebit")
                    obj.recordDetailOtrTransactioncode = "310";
                    
            }
           
          
            obj.recordDetailOstSendersreferencenumber = DateTime.Now.ToString("yyyyMMddhhssff");

            // //GROUP TRN
            if(context.Request.Params["trn"]!=null)
                 obj.recordDetailOtrTrn = context.Request.Params["trn"];
            obj.recordDetailOtrRelatedtrn = "BOC" + DateTime.Now.ToString("yyyyMMddhhssf");

            // //GROUP AMOUNT
            if (context.Request.Params["amount"] != null && context.Request.Params["amount"].ToString().Trim() != "")
                 obj.recordDetailOtrAmount = Convert.ToDecimal(context.Request.Params["amount"]).ToString();//.Replace(",","").Replace(".","").Substring(0,context.Request.Params["amount"].Trim().Length-3);
                //obj.recordDetailOtrAmount = Convert.ToDecimal(context.Request.Params["amount"]).ToString("#,###");
            if (context.Request.Params["currency"] != null)
                obj.recordDetailOstCurrency = context.Request.Params["currency"];
            //obj.recordDetailOtrValuedate = context.Request.Params["bussinesDay"];

            if (context.Request.Params["bussinesDay"] != null)
            {
                string[] splitTanggal = context.Request.Params["bussinesDay"].ToString().Trim().Split('/');

                obj.recordDetailOtrValuedate = splitTanggal[2].ToString() + splitTanggal[1].ToString() + splitTanggal[0].ToString();
            }

            if (context.Request.Params["debitParticipantsClient"] != null)
            {

                if (context.Request.Params["debitParticipantsClient"].ToString().Trim().Length > 140)
                    obj.recordDetailOstOriginatingname = context.Request.Params["debitParticipantsClient"].ToString().Substring(0, 140);
                else
                    obj.recordDetailOstOriginatingname = context.Request.Params["debitParticipantsClient"].ToString();
                
                membertRepo memberDal = new membertRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);

                membert objmember = memberDal.GetById(context.Request.Params["debitParticipantsClient"].Trim());

                obj.recordDetailOstFromaccountnumber = objmember.accnbr.Trim();
                obj.recordDetailOstFromaccountname = objmember.memname.Trim();

                obj.recordDetailOtrFrommember = objmember.memcde.Trim();
            }

            if (context.Request.Params["creditParticipantsClient"] != null)
            {

                if (context.Request.Params["creditParticipantsClient"].ToString().Trim().Length > 140)
                    obj.recordDetailOstUltimatebenefname = context.Request.Params["creditParticipantsClient"].ToString().Substring(0, 140);
                else
                    obj.recordDetailOstUltimatebenefname = context.Request.Params["creditParticipantsClient"].ToString();
                
                membertRepo memberDal = new membertRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);

                membert objmember = memberDal.GetById(context.Request.Params["creditParticipantsClient"].Trim());

                obj.recordDetailOstToaccountnumber = objmember.accnbr.Trim();
                obj.recordDetailOstToaccountname = objmember.memname.Trim();

                obj.recordDetailOtrTomember = objmember.memcde.Trim();
            }

            if (context.Request.Params["accountDebitParticipant"] != null)
                obj.recordDetailOstOriginatingnumber = context.Request.Params["accountDebitParticipant"];

            if (context.Request.Params["accountCreditParticipant"] != null)
                obj.recordDetailOstUltimatebenefaccount = context.Request.Params["accountCreditParticipant"];

            ////GROUP DETAIL
            if (context.Request.Params["remitanceInformation"] != null)
            {
                if (context.Request.Params["remitanceInformation"].ToString().Trim().Length > 96)
                    obj.recordDetailOstPaymentdetails = context.Request.Params["remitanceInformation"].ToString().Substring(0, 96);
                else
                    obj.recordDetailOstPaymentdetails = context.Request.Params["remitanceInformation"].ToString();
            }

            if (context.Request.Params["detailOfCharges"] != null)
                 obj.recordDetailOtrRecordtype = context.Request.Params["detailOfCharges"];
            if (context.Request.Params["transactionSubTypeCode"] != null)
                obj.recordDetailOtrTransactioncode = context.Request.Params["transactionSubTypeCode"];


            ////GROUP PRIORITY
            if (context.Request.Params["priority"] != null)
                obj.recordDetailOrecordPriority = context.Request.Params["priority"];

            obj.recordDetailOrecordSwiftOdatetime = DateTime.Now;
            obj.recordDetailOrecordtime = DateTime.Now;
            obj.recordDetailOrecordOhBatchreference = string.Empty;
            

            if (strRecordDal.Save(obj))
            {
                helper.Data = obj;
                helper.Message = "Data has been saved!";
                helper.IsSuccess = true;

                log = new sysTLog();
                log.logEvent = "Insert STP_RECORD_DETAIL_O_CLEARING " + typeOutgoing + "  Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = strRecordDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Insert STP_RECORD_DETAIL_O_CLEARING " + typeOutgoing + "  Error";
                log.logMessage = strRecordDal.GetErrorMessage();


            }

            log.logSource = "stp_record_detail_o_clearing.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string GetData(HttpContext context)
        {
            
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? stpRecordDetailO.Fields.recordDetailOtrRecordtype: context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());


            string parameters = string.Empty;

            //if (typeOutgoing.Trim().ToLower() == "accept")
            //    parameters = parameters.Trim().Length > 0 ? parameters + " AND UPPER(RECORD_DETAIL_ORECORD_Status) IN ('RP','WA') " : " WHERE UPPER(RECORD_DETAIL_ORECORD_Status) IN ('RP','WA')";
            //if (typeOutgoing.Trim().ToLower() == "drop")
            //    parameters = parameters.Trim().Length > 0 ? parameters + " AND UPPER(RECORD_DETAIL_ORECORD_Status) IN ('RF','RP') " : " WHERE UPPER(RECORD_DETAIL_ORECORD_Status) IN ('RF','RP')";
            //if (typeOutgoing.Trim().ToLower() == "repair")
            //    parameters = parameters.Trim().Length > 0 ? parameters + " AND UPPER(RECORD_DETAIL_ORECORD_Status) = 'RF' " : " WHERE UPPER(RECORD_DETAIL_ORECORD_Status) = 'RF'";

            if (context.Request.Params["isclearing"] != null)
            {
                
                if (context.Request.Params["isclearing"].ToString().Equals("prefundkredit"))
                    parameters = (!string.IsNullOrEmpty(parameters) ? parameters + "AND RECORD_DETAIL_OTR_TransactionCode='300'" : " WHERE RECORD_DETAIL_OTR_TransactionCode='300'");

                if (context.Request.Params["isclearing"].ToString().Equals("prefunddebit"))
                    parameters = (!string.IsNullOrEmpty(parameters) ? parameters + "AND RECORD_DETAIL_OTR_TransactionCode='310'" : " WHERE RECORD_DETAIL_OTR_TransactionCode='310'");

                if (context.Request.Params["isclearing"].ToString().Equals("topprefunddebit"))
                    parameters = (!string.IsNullOrEmpty(parameters) ? parameters + "AND RECORD_DETAIL_OTR_TransactionCode='311'" : " WHERE RECORD_DETAIL_OTR_TransactionCode='311'");

                if (context.Request.Params["isclearing"].ToString().Equals("topprefundkredit1"))
                    parameters = (!string.IsNullOrEmpty(parameters) ? parameters + "AND RECORD_DETAIL_OTR_TransactionCode='301'" : " WHERE RECORD_DETAIL_OTR_TransactionCode='301'");

                if (context.Request.Params["isclearing"].ToString().Equals("topprefundkredit2"))
                    parameters = (!string.IsNullOrEmpty(parameters) ? parameters + "AND RECORD_DETAIL_OTR_TransactionCode='302'" : " WHERE RECORD_DETAIL_OTR_TransactionCode='302'");
            }
            
            //if (typeOutgoing.Trim().ToLower() == "pembayaran")
            //{
            //    parameters = parameters.Trim().Length > 0 ? parameters + " AND UPPER(RECORD_DETAIL_ORECORD_Status) = 'WA' " : " WHERE UPPER(RECORD_DETAIL_ORECORD_Status) = 'WA'";

            //    if (context.Request.Params["ispayment"] != null)
            //    {
            //        if(context.Request.Params["ispayment"].ToString().Contains("single"))
            //            parameters += " AND RECORD_DETAIL_ORECORD_MT='103'";
                    
            //        if(context.Request.Params["ispayment"].ToString().Contains("general"))
            //            parameters += " AND RECORD_DETAIL_ORECORD_MT='202'";

            //        if (context.Request.Params["ispayment"].ToString().Contains("payment"))
            //            parameters += " AND RECORD_DETAIL_ORECORD_MT NOT IN('103','202')";
 
            //    }

                
            //}

            
            string valuedate = ((context.Request.Params["valuedate"]) == null ? string.Empty : context.Request.QueryString["valuedate"].ToString());
            string trn = ((context.Request.Params["trn"]) == null ? string.Empty : context.Request.QueryString["trn"].ToString());
            string batchref = ((context.Request.Params["batchref"]) == null ? string.Empty : context.Request.QueryString["batchref"].ToString());
            string status = ((context.Request.Params["status"]) == null ? string.Empty : context.Request.QueryString["status"].ToString());
            string refno = ((context.Request.Params["refno"]) == null ? string.Empty : context.Request.QueryString["refno"].ToString());
            string tomember = ((context.Request.Params["tomember"]) == null ? string.Empty : context.Request.QueryString["tomember"].ToString());


            parameters = !string.IsNullOrEmpty(valuedate) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_OTR_ValueDate LIKE '%" + valuedate + "%'" : " WHERE RECORD_DETAIL_OTR_ValueDate LIKE '%" + valuedate + "%'")
                                 : parameters;

            parameters = !string.IsNullOrEmpty(trn) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_OTR_TRN LIKE '%" + trn + "%'" : " WHERE RECORD_DETAIL_OTR_TRN LIKE '%" + trn + "%'")
                                 : parameters;

            parameters = !string.IsNullOrEmpty(batchref) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_ORECORD_OH_BatchReference LIKE '%" + batchref + "%'" : " WHERE RECORD_DETAIL_ORECORD_OH_BatchReference LIKE '%" + batchref + "%'")
                                 : parameters;


            parameters = !string.IsNullOrEmpty(status) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_ORECORD_Status LIKE '%" + status + "%'" : " WHERE RECORD_DETAIL_ORECORD_Status LIKE '%" + status + "%'")
                                 : parameters;

            parameters = !string.IsNullOrEmpty(refno) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_ORECORD_RefNo LIKE '%" + status + "%'" : " WHERE RECORD_DETAIL_ORECORD_RefNo LIKE '%" + refno + "%'")
                                 : parameters;

            parameters = !string.IsNullOrEmpty(tomember) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_OTR_ToMember LIKE '%" + tomember + "%'" : " WHERE RECORD_DETAIL_OTR_ToMember LIKE '%" + tomember + "%'")
                                 : parameters;

            
            int totalCount = Convert.ToInt32(strRecordDal.SelectScalar(SQL.Function.Aggregate.Count, stpRecordDetailO.Fields.recordDetailOtrRecordtype, parameters));

            decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
            int totalPages = Convert.ToInt32(dc);

            List<stpRecordDetailO> pagedList = strRecordDal.GetList(pageSize, page, sidx, sord, parameters);

            var query = from clearing in pagedList
                        //join product in productDTO on subproduct.productId equals product.id
                        select new
                        {
                            clearing.recordDetailOtrRelatedtrn,
                            clearing.recordDetailOtrValuedate,
                            clearing.recordDetailOrecordStatus,
                            clearing.recordDetailOrecordRsncde,
                            clearing.recordDetailOtrTomember,
                            clearing.recordDetailOtrTrn,
                            recordDetailOtrAmount = clearing.recordDetailOtrAmount==string.Empty?string.Empty : Convert.ToDecimal(clearing.recordDetailOtrAmount).ToString("#,###.00")
                            
                           
                        };

            if (!string.IsNullOrEmpty(strRecordDal.GetErrorMessage()))
            {
                log = new sysTLog();
                log.logEvent = "GetData STP_RECORD_DETAIL_O_CLEARING " + typeOutgoing + "  Error";
                log.logMessage = strRecordDal.GetErrorMessage();
            }
            else
            {
                log = new sysTLog();
                log.logEvent = "View Data STP_RECORD_DETAIL_O_CLEARING " + typeOutgoing + "  Success";
                log.logMessage = string.Empty;
            }

            log.logSource = "stp_record_detail_o_clearing.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = query,

            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }

        public string GetMemberByCode(HttpContext context)
        {
            base.ProcessRequest(context);

            RTGS.Library.Report.ReportSptDetailRecordO reportDal = new RTGS.Library.Report.ReportSptDetailRecordO(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);

            string membercode = Convert.ToString(context.Request.Params["membercode"]);

            System.Data.DataTable dt = reportDal.GetMemberByMemberCode(membercode);
            //List<rExchangeRateDTO> list = mgr.GetListDTO();
            //var result = list.Where(x => x.exchangeRateTypeId == jeniskurs);

            string result = string.Empty;
            
            if(dt.Rows.Count>0)
                result = dt.Rows[0]["memcde"].ToString() + "|" + dt.Rows[0]["accnbr"].ToString();

            return Newtonsoft.Json.JsonConvert.SerializeObject(result);
        }

        private string Delete(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            bool isSuccess = true;
            string[] ids = context.Request.Params["id"].Split(',');
            foreach (string id in ids)
            {
                isSuccess = strRecordDal.Delete(id);
                if (!isSuccess) break;
            }

            if (isSuccess)
            {
                helper.IsSuccess = true;
                helper.Message = "Data has been deleted!";

                log = new sysTLog();
                log.logEvent = "Delete STP_RECORD_DETAIL_O_CLEARING Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = strRecordDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Delete  STP_RECORD_DETAIL_O_CLEARING Error";
                log.logMessage = strRecordDal.GetErrorMessage();
            }

            log.logSource = "stp_config.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        #endregion

    
    }
}